package cn.zynworld.fansafe.jwt.core;

import cn.zynworld.fansafe.common.utils.CodecUtils;
import cn.zynworld.fansafe.common.utils.JsonUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;

import java.util.HashMap;
import java.util.Map;

/**
 * 以键值对方式存储Jwt信息对象
 */
public class JwtBean {

    //敏感值 用于对jwt HA256加密
    private final String SECRET;

    private Map<String,Object> headMap = new HashMap<String, Object>();
    private Map<String,Object> playloadMap = new HashMap<String, Object>();


    private static Gson gson = new GsonBuilder().create();
    private static JsonParser jsonParser = new JsonParser();


    public JwtBean(String secret){
        this.SECRET = secret;
    }



    /**
     * 为jwt添加头信息
     */
    public JwtBean addHead(String key,Object value){
        headMap.put(key,value);
        return this;
    }

    /**
     * 为jwt添加荷载
     */
    public JwtBean addPlayload(String key,Object value){
        playloadMap.put(key,value);
        return this;
    }

    public Map<String, Object> getHeadMap() {
        return headMap;
    }

    public Map<String, Object> getPlayloadMap() {
        return playloadMap;
    }

    public Object getHead(String key){
        return headMap.get(key);
    }

    public <T> T getHead(String key,Class<T> type){
        return (T) headMap.get(key);
    }

    public Object getPlayload(String key){
        return playloadMap.get(key);
    }
    public <T> T getPlayload(String key,Class<T> type ){
        return (T) playloadMap.get(key);
    }

    public String getHeadJson(){
        return gson.toJson(headMap);
    }


    public String getPlayloadJson(){
        return gson.toJson(playloadMap);
    }

    public JwtBean setHeadMap(Map<String, Object> headMap) {
        this.headMap = headMap;
        return this;
    }

    public JwtBean setPlayloadMap(Map<String, Object> playloadMap) {
        this.playloadMap = playloadMap;
        return this;
    }

    //将JwtBean对象转换为字符串
    public String toJwtString(){
        String jwt = null;
        String headJson = gson.toJson(headMap);
        String playload = gson.toJson(playloadMap);


        //base64
        headJson = CodecUtils.encodeBase64(headJson);
        playload = CodecUtils.encodeBase64(playload);

        jwt = headJson + "." +playload;
        jwt = jwt + "." + CodecUtils.getSHA256Str(jwt + this.SECRET);
        return  jwt;
    }

    @Override
    public String toString() {
        return "JwtBean{" +
                "SECRET='" + SECRET + '\'' +
                ", headMap=" + headMap +
                ", playloadMap=" + playloadMap +
                '}';
    }
}
